﻿using System;

namespace Creventive.Wpf.ShellFactory.Services
{
    internal class LambdaServiceFactory<T> : IServiceFactory<T>
        where T : class
    {
        private InstantiationMode instantiationMode;
        private Func<T> createObjectCallback;
        private T singletonInstance;

        public LambdaServiceFactory(Func<T> createObjectCallback, InstantiationMode instantiationMode)
        {
            this.createObjectCallback = createObjectCallback;
            this.instantiationMode = instantiationMode;
        }

        public T Create(IServiceContainer serviceContainer)
        {
            if (this.instantiationMode == InstantiationMode.Singleton)
            {
                if (this.singletonInstance == null)
                    this.singletonInstance = this.createObjectCallback.Invoke();
                return this.singletonInstance;
            }
            else
            {
                var instance = this.createObjectCallback.Invoke();
                return instance;
            }
        }

        object IServiceFactory.Create(IServiceContainer serviceContainer)
        {
            return this.Create(serviceContainer);
        }
    }
}